package com.example.demo.zk;

import org.redisson.Redisson;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;

/**
 * Created by alva on 18/6/13.
 */
public class RedissonManager {
    private static final String RAtomicName = "genId_";

    private static Config config = new Config();
    private static RedissonClient redisson;

    public static void init(){
        try {
            Config config = new Config();
//指定使用单节点部署方式
            config.useSingleServer().setAddress("redis://127.0.0.1:6379");
//                    /.setPassword("hzfund");
//创建客户端(发现这一非常耗时，基本在2秒-4秒左右)
            RedissonClient myRedisson = Redisson.create(config);
            redisson = myRedisson;
            //清空自增的ID数字
            RAtomicLong atomicLong = redisson.getAtomicLong(RAtomicName);
            atomicLong.set(1);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static RedissonClient getRedisson(){
        init();
        return redisson;
    }

    /** 获取redis中的原子ID */
    public static Long nextID(){
        RAtomicLong atomicLong = getRedisson().getAtomicLong(RAtomicName);
        atomicLong.incrementAndGet();
        return atomicLong.get();
    }
}
